/*
 * network_net_helper.c
 *
 *  Created on: 12.07.2012
 *      Author: Sebastian
 *
 *  Funktionen die bei der Blauzahn Kommunikation helfen
 */

#include <string.h>

#include "network.h"
#include "network_private.h"
#include "network_debug.h"
#include "ecrobot_interface.h"

/*------ net helpers------*/

/*
 * sendet einen packet string
 */
int sendMsg(char* buffer) {
	if (ecrobot_get_bt_status() == BT_STREAM) {
		int send = ecrobot_send_bt(buffer, 0, MSG_SIZE);
		if (send == MSG_SIZE) {
			return NW_TRUE;
		}
	}
	return NW_FALSE;
}

/*
 * versucht packet string zulesen bricht nach einer secunde ohne zeichen ab
 */
int readMsg(char* buffer) {
	int write = 0;
	int end = TIME_OUT + systick_get_ms();
	int read = NW_TRUE;
	int received = 0;

	while (read) {
		if (ecrobot_get_bt_status() == BT_STREAM) {
			received = ecrobot_read_bt(buffer, write, MSG_SIZE - write);
			write += received;

			buffer[write] = '\0';

			if (received) {
				end = TIME_OUT + systick_get_ms();
			}

			if (write >= MSG_SIZE) {
				read = NW_FALSE;
			}
		} else {
			read = NW_FALSE;
		}

		if (systick_get_ms() > end) {
			read = NW_FALSE;
		}

	}

	return (write == MSG_SIZE) ? NW_TRUE : NW_FALSE;
}

/*
 * schickt eine error Nachricht
 */
int sendError(nw_teamType me, nw_teamType to, int err) {
#if defined(DEBUG)
	message errMsg;
	char errBuf[MSG_SIZE];

	errMsg.from = me;
	errMsg.to = to;
	errMsg.type = ERR;
	memcpy(errMsg.data, (char*) msgErrNames[err], DATA_SIZE);

	if (serialisation(&errMsg, errBuf)) {
		if (sendMsg(errBuf)) {
			return NW_TRUE;
		}
	}
#endif
	return NW_FALSE;
}

/*
 * Baut die Verbindung auf
 */
int connect() {
	int btStatus = ecrobot_get_bt_status();
	if (btStatus != BT_STREAM && btStatus == BT_CONNECTED) {
		debug(NET_LINE, "disconnecting...");
		ecrobot_term_bt_connection();
	}

	while (ecrobot_get_bt_status() != BT_STREAM) {
		debug(NET_LINE, "connecting...");
		ecrobot_init_bt_slave("pod");
	}

	debug(NET_LINE, "connected");
	return NW_TRUE;
}
